var util = require('../../utils/util.js')

var user_id
var page = 1
var pageSize = 10
var orders = []

function getOrderList (that) {
  if (that.data.activeIndex === 0) {
    that.setData({
      inputVal: ''
    })
    getApp().sp()
    wx.request({
      url: getApp().globalData.javaurl + '/main/driverOrderDetail/getAcceptHistoryListByPageV2',
      //getDriverOrderDetailListByPage
      //getDriverOrderDetailListByPageV2
      method: 'POST',
      data: {
        "stateStr": "1",
        "pageNumber": page,
        "pageSize": pageSize,
        "sortName": "bind_time",
        "sortOrder": " desc"
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "Authorization": wx.getStorageSync('token')
      },
      success: function (res) {
        getApp().hp()
        wx.stopPullDownRefresh()
        let enable_pull_down = true
        if (res.data.isSuccess === 1) {
          if (orders.length === res.data.data.total) {
            enable_pull_down = false
          }
          if (enable_pull_down) {
            for (let i = 0; i < res.data.data.rows.length; i++) {
              orders.push(res.data.data.rows[i])
            }
            if (res.data.data.rows.length < pageSize) {
              that.setData({
                more: 0
              })
            }
            that.setData({
              orders: orders
            })
            page++
          } else {
            that.setData({
              more: 0
            })
          }
        } else {
          that.setData({
            more: 0
          })
          if (page === 1) {
            that.setData({
              orders: [],
              more: 0
            })
          } else {
            that.setData({
              more: 0
            })
          }
        }
      }
    })
  } else {
    that.setData({
      inputVal: ''
    })
    getApp().sp()
    user_id = wx.getStorageSync('user_id')
    wx.request({
      url: getApp().globalData.apiurl + 'getOrderList',
      method: 'POST',
      data: {
        "user_id": user_id,
        "page": page,
        "type": parseInt(that.data.activeIndex) + 1,
        "like": that.data.inputVal,
        "pagesize": pageSize
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res.data)
        getApp().hp()
        wx.stopPullDownRefresh()
        if (res.data.isSuccess == 1) {
          for (var i = 0; i < res.data.data.length; i++) {
            orders.push(res.data.data[i])
          }
          if (res.data.data.length < 20) {
            that.setData({
              more: 0
            })
          }
          that.setData({
            orders: orders
          })
          page++
        } else {
          that.setData({
            more: 0
          })
          if (page == 1) {
            that.setData({
              orders: [],
              more: 0
            })
          } else {
            that.setData({
              more: 0
            })
          }
        }
      }
    })
  }
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs: ["重箱出场", "空箱入场", "空箱出场", "重箱入场"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLength: 0,
    more: 1,
    need_pad: 0,
    inputShowed: false,
    inputVal: ""
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowWidth)
        that.setData({
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex,
          sliderLength: res.windowWidth / that.data.tabs.length
        })
      }
    })
    orders = []
    page = 1
    that.setData({
      need_pad: wx.getStorageSync('need_pad')
    })
    getOrderList(that)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    page = 1
    orders = []
    getOrderList(this)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    getOrderList(this)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: parseInt(e.currentTarget.id)
    })
    this.onPullDownRefresh()
  },

  open_ewm: function (e) {

    wx.navigateTo({
      url: '/pages/qrcode/qrcode?order_no=' + e.currentTarget.dataset.order_no + '&container_no=' + e.currentTarget.dataset.container_no
    })

    // var url = "http://pan.baidu.com/share/qrcode?w=600&h=600&url="+e.currentTarget.dataset.order_no;
    // wx.previewImage({
    //   current: url, // 当前显示图片的http链接
    //   urls: [url] // 需要预览的图片http链接列表
    // })

  },

  scan_pound: function (e) {
    let that = this
    let id = e.currentTarget.dataset.id
    let container_no = e.currentTarget.dataset.container_no
    let index = e.currentTarget.dataset.index
    let order = orders[index]
    wx.scanCode({
      success: function (res) {
        let arr = res.result.split(",")
        wx.request({
          url: getApp().globalData.javaurl + '/main/driverOrderDetail/uploadPound',
          method: 'POST',
          data: {
            "id": id,
            "containerNo": container_no,
            "subOrderId": order.subOrderId,
            "fleetOrderDetailId": order.fleetOrderDetailId,
            "grossWeightTime": arr[5],
            "grossWeight": arr[6],
            "tareWeightTime": arr[7],
            "tareWeight": arr[8],
            "netWeight": arr[9],
            "poundNo": arr[10]
          },
          header: {
            "content-type": "application/x-www-form-urlencoded",
            "Authorization": wx.getStorageSync('token')
          },
          success: function (res) {
            getApp().hp()
            if (res.data.isSuccess === 1) {
              wx.request({
                url: getApp().globalData.javaurl + '/main/driverOrderDetail/getDriverOrderDetailListByPage',
                method: 'POST',
                data: {
                  "id": order.id
                },
                header: {
                  "content-type": "application/x-www-form-urlencoded",
                  "Authorization": wx.getStorageSync('token')
                },
                success: function (res) {
                  if (res.data.isSuccess === 1) {
                    if (1 === res.data.data.total) {
                      orders[index] = res.data.data.rows[0]
                      that.setData({
                        orders: orders
                      })
                      getApp().alert("磅单上传成功！")
                    }
                  }
                }
              })
            } else {
              getApp().alert(res.data.msg)
            }
          }
        })
      }
    })
  },
  delete_empty_order: function (e) {
    var id = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index
    var that = this
    wx.showModal({
      title: '警告！',
      content: "删除该返箱后，信息将无法恢复！",
      cancelText: "我再想想",
      confirmText: "确定删除",
      confirmColor: "#c71d23",
      success: function (res) {
        if (res.confirm) {
          getApp().sp()
          wx.request({
            url: getApp().globalData.apiurl + 'unbindEmptyContainer',
            method: 'POST',
            data: {
              "user_id": user_id,
              "id": id
            },
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            success: function (res) {
              getApp().hp()
              console.log(res.data)
              if (res.data.isSuccess == 1) {
                orders.splice(index, 1)
                that.setData({
                  orders: orders
                })
                getApp().alert("删除成功！")
              } else {
                getApp().alert(res.data.res)
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  delete_order: function (e) {
    let that = this
    let id = e.currentTarget.dataset.id
    let container_no = e.currentTarget.dataset.container_no
    let index = e.currentTarget.dataset.index
    wx.showModal({
      title: '警告！',
      content: "删除该单后，箱号会回到箱号池中，你录入的磅单信息将无法恢复！",
      cancelText: "我再想想",
      confirmText: "确定删除",
      confirmColor: "#c71d23",
      success: function (res) {
        if (res.confirm) {
          getApp().sp()
          wx.request({
            url: getApp().globalData.javaurl + '/main/driverOrderDetail/deleteDriverOrder2',
            method: 'POST',
            data: {
              "id": id,
              "containerNo": container_no
            },
            header: {
              "content-type": "application/x-www-form-urlencoded",
              "Authorization": wx.getStorageSync('token')
            },
            success: function (res) {
              getApp().hp()
              console.log(res.data)
              if (res.data.isSuccess === 1) {
                orders.splice(index, 1)
                that.setData({
                  orders: orders
                })
                getApp().alert("删除成功！")
              } else {
                getApp().alert(res.data.res)
              }
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  addMedia (e) {
    let index = e.currentTarget.dataset.index
    let order = orders[index]
    let activeIndex = this.data.activeIndex
    let heavy_or_empty = ''
    let in_or_out = ''
    if (activeIndex === 0) {
      wx.navigateTo({
        url: '/pages/heavy_out/heavy_out?isAddMedia=true&order=' + JSON.stringify(order)
      })
    } else if (activeIndex === 1) {
      heavy_or_empty = 0
      in_or_out = 2
    } else if (activeIndex === 2) {
      heavy_or_empty = 0
      in_or_out = 1
    } else if (activeIndex === 3) {
      heavy_or_empty = 1
      in_or_out = 2
    } else {
      return
    }
    wx.navigateTo({
      url: '/pages/bind_other/bind_other?heavy_or_empty=' + heavy_or_empty + '&in_or_out=' + in_or_out + '&isEdit=true&order=' + JSON.stringify(order)
    })
  },

  /***** 搜索一系列 start ****/
  /**
   * TODO(搜索框输入ing)
   * @auther zhangQ
   * @date 2018/1/25 17:22
   **/
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    })
    if (!(e.detail.value + '')) {
      this.backDisplayDriverList()
      return
    }
    let orderList = this.data.orders
    console.log(orderList)
    for (var i = 0; i < orderList.length; i++) {
      if (orderList[i].containerNo.indexOf(e.detail.value) >= 0) {
        orderList[i].isShow = !true
      } else {
        orderList[i].isShow = !false
      }
    }
    this.setData({
      orders: orderList
    })
  },
  /**
   * TODO(搜索框被点击)
   * @auther zhangQ
   * @date 2018/1/25 17:22
   **/
  searchInput: function () {
    this.setData({
      inputShowed: true
    })
  },
  hideInput: function () {
    this.setData({
      inputShowed: false
    })
    this.clearInput()
    // 回显old driverList
    this.backDisplayDriverList()

  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    })
    this.backDisplayDriverList()
  },
  /**
   * TODO(回显)
   * @auther zhangQ
   * @date 2018/1/25 17:47
   **/
  backDisplayDriverList () {
    let orderList = this.data.orders
    for (var i = 0; i < orderList.length; i++) {
      orderList[i].isShow = !true
    }
    this.setData({
      orders: orderList
    })
  }
  /***** 搜索一系列 end ****/
})